import 'package:app/api/delivery/index.dart';
import 'package:app/api/material-pick/material.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

/// 生产退料
class ProductMaterialReturn extends StatefulWidget{

  const ProductMaterialReturn({super.key,});

  @override
  State<ProductMaterialReturn> createState() => _ProductMaterialReturnState();

}

class _ProductMaterialReturnState extends State<ProductMaterialReturn>{

  final FocusNode _firstFocusNode = FocusNode();
  // 站点
  String _code = '';

  List<dynamic> _list = [];

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  // 设置值
  void setValue(String key, String value){
    switch (key) {
      case '_code': setState(() => _code = value); break;
      default:
        throw Exception('key error');
    }
  }

  void clear(){
    setState((){
      _code = '';
      _list = [];
    });
  }

  /// 确认
  void confirm(){
    Forms.validate(_formKey!).then((valid) async {
      if(valid){
        MaterialApi.of(context).materialBacks(_code).then((res){
          if(StringUtils.isNotNull(res.data)){
            setState(() => _list = res.data['data']);
            hideKeyBorder();
          }
        });
      }
    });
  }

  /// 提交
  void submit(){
    if(_list.isEmpty){
      Error.of(context).show('没有可配送的物料');
      return;
    }
    String pickId = _list[0]['pickId'];
    Confirm.of(context).show('确定要开始配送么', (){
      Delivery.of(context).immediately(pickId).then((res){
        Navigator.pop(context);
        if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
          Success.of(context).show('配送单创建成功，请等待');
        }
      });
    });
  }

  /// 解绑物料
  void unbind(){
    Forms.validate(_formKey!).then((valid) async {
      if(valid){
        Confirm.of(context).show('确定要解绑物料么', (){
          MaterialApi.of(context).unbind(_code).then((res){
            Navigator.pop(context);
            if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
              clear();
              Success.of(context).show('物料解绑成功');
            }
          });
        });
      }
    });
  }

  void go(String path){
    Navigator.pushNamed(context, path);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '生产退料'),
      body: GestureDetector(
          onTap: hideKeyBorder,
          child: Column(
            children: [
              Group(
                title: '操作',
                height: 120,
                context: context,
                child: Menu(
                    context: context,
                    items: [
                      MenuItem(
                        icon: const Icon(Icons.add,color: Colors.white,size: 40),
                        text: "物料绑定",
                        color: const Color.fromARGB(255, 154, 204, 109),
                        onTap: ()=>go('/product-material-return-detail'),
                      ),
                      MenuItem(
                        icon: const Icon(Icons.unarchive_outlined, color: Colors.white,size: 40),
                        text: "物料解绑",
                        color: const Color.fromARGB(255, 107, 200, 171),
                        onTap: ()=>{unbind()},
                      ),
                      MenuItem(
                        icon: const Icon(Icons.call, color: Colors.white,size: 40),
                        text: "空托呼叫",
                        color: const Color.fromARGB(255, 109, 183, 234),
                        onTap: ()=>go('/empty-pallet-call'),
                      ),
                    ]
                ),
              ),
              Group(
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                        formKey: _formKey,
                        formItem: [
                          FormItem(
                            onEntry: (String value) =>{confirm()},
                            type: 'input',
                            labelWidth: 90,
                            focusNode: _firstFocusNode,
                            labelText: '站点码',
                            placeholder: '请扫站点码',
                            filedName: 'code',
                            value: _code,
                            icon: const Icon(Icons.qr_code_scanner_rounded),
                            iconOnTap: scan,
                            onChange: (value) => setValue('_code', value),
                            rules: const {'code': [{'required': true, 'message': '站点号不能为空'}]},
                          ),
                        ]
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListContainer(
                  title: '物料清单',
                  length: _list.length,
                  children: (index) {
                    return [
                      ListTitle(
                        context: context,
                        label: _list[index]['itemName'],
                      ),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '托盘号：',
                          value: _list[index]['container'],
                        ),
                      ]),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '退库单号：',
                          value: _list[index]['erpInvBillCode'],
                        )
                      ]),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '物料编号：',
                          value: _list[index]['itemCode'],
                        ),
                        HorizontalItem(
                          label: '数量：',
                          value: _list[index]['itemQty'].toString() + ' ' + _list[index]['itemUnit'],
                          fontColor: Colors.white,
                          valueBackground: const Color.fromARGB(255, 69, 228, 194),
                        )
                      ]),
                    ];
                  },
                ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
                  child: Button(
                    onPressed: submit,
                    label: '开始配送',
                    height: 60,
                    fontSize: 18,
                  ),
                ),
              ),
            ],
          )
      ),
    );
  }

}